# 把excelip.txt里的每行一个IP地址，进行判断是否有有效的IP地址，然后进行IP地址去重后按从小到大顺序写入excelip_ban.txt
import ipaddress

input_filename = "excelip.txt"
output_filename = "excelip_ban.txt"
valid_ips = set()

# 排除的 IP 地址范围
excluded_networks = [
    ipaddress.ip_network("127.0.0.0/8"),
    ipaddress.ip_network("192.168.0.0/16")
]

# 读取 excelip.txt 文件并进行有效性判断和排除
with open(input_filename, "r") as file:
    for line in file:
        ip = line.strip()
        try:
            ip_obj = ipaddress.ip_address(ip)
            if not any(ip_obj in network for network in excluded_networks):
                valid_ips.add(ip)
        except ValueError:
            print(f"{ip} 不是一个有效的 IP 地址")

# 对有效的 IP 地址进行排序
sorted_ips = sorted(valid_ips, key=lambda x: ipaddress.ip_address(x))

# 写入 excelip_ban.txt 文件
with open(output_filename, "w") as file:
    for ip in sorted_ips:
        file.write(ip + "\n")

print("转换完成，结果已写入 excelip_ban.txt 文件。")